﻿using Microsoft.Win32;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mbs.Utils
{
    public class RegistryHelper
    {
        public static async Task<ConcurrentDictionary<string, string>> FindRegistryValuesAsync(string keyPath, string targetValue)
        {
            var foundItems = new ConcurrentDictionary<string, string>();
            var tasks = new List<Task>();
            try
            {
                using (RegistryKey baseKey = Registry.LocalMachine.OpenSubKey(keyPath))
                {
                    if (baseKey != null)
                    {
                        foreach (var subKeyName in baseKey.GetSubKeyNames())
                        {
                            // 创建并启动一个新的任务来处理每个子键
                            var task = ProcessSubKeyAsync(subKeyName, keyPath, targetValue, foundItems);
                            tasks.Add(task);
                        }

                        await Task.WhenAll(tasks);
                    }
                }
            }
            catch (Exception)
            {

            }
            return foundItems;
        }

        static async Task ProcessSubKeyAsync(string subKeyName, string parentPath, string targetValue, ConcurrentDictionary<string, string> foundItems)
        {
            string fullKeyPath = $"{parentPath}\\{subKeyName}";

            try
            {
                using (RegistryKey subKey = Registry.LocalMachine.OpenSubKey(fullKeyPath))
                {
                    if (subKey != null)
                    {
                        // 同步处理当前子键的值
                        foreach (var valueName in subKey.GetValueNames())
                        {
                            var value = subKey.GetValue(valueName) as string;
                            if (value == targetValue)
                            {
                                //foundItems.TryAdd($"{fullKeyPath}\\{valueName}", valueName);
                                foundItems.TryAdd($"{fullKeyPath}", valueName);
                            }
                        }

                        // 递归处理子键
                        foreach (var childSubKeyName in subKey.GetSubKeyNames())
                        {
                            // 直接调用，因为在Task.Run中已经是异步上下文
                            await ProcessSubKeyAsync(childSubKeyName, fullKeyPath, targetValue, foundItems);//.ConfigureAwait(false);
                        }
                    }
                }
            }
            catch (UnauthorizedAccessException)
            {
                // 处理无权限访问的情况，例如打印日志或跳过该键
                //Console.WriteLine($"无权限访问注册表键: {fullKeyPath}");
            }
            catch (Exception ex)
            {
                // 其他异常也应适当处理
                //Console.WriteLine($"处理注册表键 {fullKeyPath} 时发生错误: {ex.Message}");
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="paths"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static void ModifyCamera(ConcurrentDictionary<string, string> paths, string value)
        {
            foreach (var path in paths)
            {
                try
                {
                    using (RegistryKey key = Registry.LocalMachine.OpenSubKey(path.Key.Replace("HKLM\\", ""), true))
                    {
                        if (key != null)
                        {
                            string _key = path.Value;
                            if (string.IsNullOrEmpty(_key)) { _key = ""; }
                            key.SetValue(_key, value);
                        }
                        else
                        {
                            //MessageBox.Show($"无法打开注册表键 '{path}'。");
                        }
                    }
                }
                catch (UnauthorizedAccessException)
                {
                    //MessageBox.Show($"没有足够的权限访问注册表键 '{path}'。请以管理员身份运行此程序。");
                }
                catch (Exception ex)
                {
                    //MessageBox.Show($"修改注册表键 '{path}' 时发生错误: {ex.Message}");
                }
            }
        }


        // 写入注册表
        public static bool WriteToRegistry(string keyName, string keyValue)
        {
            try
            {

                RegistryKey hkcu = Registry.CurrentUser;
                RegistryKey software = hkcu.CreateSubKey(@"Software\ObsAssistant");
                if (software == null)
                    return false;

                software.SetValue(keyName, keyValue);
                software.Close();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        // 读取注册表
        public static string ReadFromRegistry(string keyName)
        {
            try
            {
                RegistryKey hkcu = Registry.CurrentUser;
                RegistryKey software = hkcu.OpenSubKey(@"Software\ObsAssistant");
                if (software == null)
                    return "";

                string keyValue = software.GetValue(keyName).ToString();
                software.Close();
                return keyValue;
            }
            catch (Exception)
            {
                return "";
            }
        }

        // 删除注册表项
        public static  bool DeleteFromRegistry(string keyName)
        {
            try
            {
                RegistryKey hkcu = Registry.CurrentUser;
                RegistryKey software = hkcu.OpenSubKey(@"Software\ObsAssistant", true);
                if (software == null)
                    return false;

                software.DeleteValue(keyName, false);
                software.Close();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}